<?php
declare (strict_types=1);

namespace app\common\controller;

use app\common\model\user\UserPermission;
use think\App;
use think\facade\Cookie;
use app\common\services\Auth;
use app\common\model\user\User;
use app\common\model\visit\Visit;
use app\common\model\platform\Platform;


/**
 * 后台控制器基础类 OldClass
 *
 * @deprecated 该类将在未来的版本中被移除，请使用 use hiduoke\controller\BaseController; 代替。
 */
abstract class BaseController
{
    /**
     * 无需登录
     * @var array
     */
    protected $notLogin = [];

    /**
     * 无需鉴权
     * @var array
     */
    protected $notCheck = [];

    /**
     * 布局模板
     * @var string
     */
    protected $layout = null;


    /**
     * 用户登录信息
     * @var User
     */
    protected $userInfo = [];

    /**
     * 子账号信息
     * @var array
     */
    protected $permission = [];

    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;


    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * @var \think\View
     */
    protected $view;

    /**
     * @var Auth
     */
    protected Auth $auth;

    protected $visit_type = "admin";

    /**
     * @var App
     */
    protected App $app;


    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->request->visit_type = $this->visit_type;
        $this->view = $this->app->view;
        $this->view->config([
            'view_path' => $app->getAppPath() . 'view' . DIRECTORY_SEPARATOR
        ]);
        $this->assign('dkSys', '<script>var dkSys = ' . json_encode($this->getDkSys()) . '</script>');
        // 验证Token
        $this->checkToken();
        //  base初始化
        $this->baseInit();
        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {

    }

    protected function checkToken()
    {
        $this->auth = new Auth();
        $token = $this->request->header('access-token', $this->request->post('access-token', Cookie::get('access-token')));
        $this->auth->init($token);
        if (!$this->auth->match($this->notLogin)) {
            //判断是否需要登录
            if ($this->auth->isLogin()) {
                $this->userInfo = $this->auth->getUserinfo();
            } else {
                if ($this->request->server("HTTP_SEC_FETCH_MODE") == 'navigate') {
                    to('/admin');
                } else {
                   showMessage("登录状态过期，请重新登录", "error", '/admin', 401);
                }
            }
            //判断是否要验证权限
            if (!$this->auth->match($this->notCheck) && $this->userInfo) {
                if (!$this->auth->check()) {
                    showMessage("当前接口没有权限访问", "error", '/admin', 402);
                }
                //判断是否效验平台权限
                $is_admin = $this->userInfo['is_admin'] ?? 0;
                if (get_plaid() && !$is_admin) {
                    $platform = Platform::where(['uid' => $this->userInfo['uid'], 'plaid' => get_plaid()])->count();
                    $permission = UserPermission::where(['uid' => $this->userInfo['uid'], 'plaid' => get_plaid()])->find();
                    if (!$platform && !$permission) {
                        showMessage("当前平台没有权限访问", "error", '/admin', 403);
                    }
                }
            }
        }
    }

    public function baseInit()
    {
        $visit = new Visit();
        $visit->updateVisitToday($this->visit_type, get_addon());
    }

    public function getAddonsPath($name = '')
    {
        $path = $this->app->getRootPath() . 'addons/';
        if ($name) {
            $path = $path . $name . "/";
        }
        return $path;
    }


    public function getDkSys()
    {
        $dkSys = array(
            'addon_name'   => get_addon(),
            'project_type' => 'addon',
            'appid'        => get_appid(),
            'plaid'        => get_plaid()
        );
        return $dkSys;
    }

    public function error($msg = '', $result = [], $code = -1)
    {
        return json(error($msg, $result, $code));
    }

    public function success($msg = '', $result = [], $other = [], $code = 0)
    {
        return json(success($msg, $result, $other, $code));
    }

    public function json($msg = '', $result = [], $code = 0, $statusCode = 200)
    {
        return json(['msg' => $msg, 'result' => $result, 'code' => $code], $statusCode);
    }


    public function wechatUrl($controller, $action = 'index', $vars = [])
    {
        $app = config('hiduoke.wechat_app');
        $p = get_plaid();
        if ($p) {
            $vars = array_merge(['p' => $p], $vars);
        }
        return url("/$app/$controller/$action", $vars)->build();
    }

    public function douyinUrl($controller, $action = 'index', $vars = [])
    {
        $app = config('hiduoke.douyin_app');
        $p = get_plaid();
        if ($p) {
            $vars = array_merge(['p' => $p], $vars);
        }
        return url("/$app/$controller/$action", $vars)->build();
    }

    public function workWechatUrl($controller, $action = 'index', $vars = [])
    {
        $app = config('hiduoke.work_wechat_app');
        $p = get_plaid();
        if ($p) {
            $vars = array_merge(['p' => $p], $vars);
        }
        return url("/$app/$controller/$action", $vars)->build();
    }

    public function adminUrl($controller, $action = 'index', $vars = [])
    {
        $app = config('hiduoke.admin_app');
        return url("/$app/$controller/$action", $vars)->build();
    }

    public function addonUrl($addon_name, $controller, $action = 'index', $vars = [], $domain = false)
    {
        $p = get_plaid();
        if ($p) {
            $vars = array_merge(['p' => $p], $vars);
        }
        return url("/$addon_name/$controller/$action", $vars)->domain($domain)->build();
    }

    /**
     * 加载模板输出
     * @param string $template
     * @param array $vars 模板文件名
     * @return false|mixed|string   模板输出变量
     * @throws \think\Exception
     */
    protected function fetch($template = '', $vars = [])
    {
        return $this->view->fetch($template, $vars);
    }

    /**
     * 渲染内容输出
     * @access protected
     * @param string $content 模板内容
     * @param array $vars 模板输出变量
     * @return mixed
     */
    protected function display($content = '', $vars = [])
    {
        return $this->view->display($content, $vars);
    }

    /**
     * 模板变量赋值
     * @access protected
     * @param mixed $name 要显示的模板变量
     * @param mixed $value 变量的值
     * @return $this
     */
    protected function assign($name, $value = '')
    {
        $this->view->assign([$name => $value]);

        return $this;
    }

    /**
     * 初始化模板引擎
     * @access protected
     * @param array|string $engine 引擎参数
     * @return $this
     */
    protected function engine($engine)
    {
        $this->view->engine($engine);

        return $this;
    }
}
